package cn.tpshion.devops.node;

import cn.tpshion.devops.common.constant.NodeConstant;
import cn.tpshion.devops.common.enums.MsgType;
import cn.tpshion.devops.common.enums.NodeType;
import cn.tpshion.devops.domain.entity.MsgData;
import cn.tpshion.devops.domain.entity.NodeData;
import cn.tpshion.devops.node.data.OSSData;
import cn.tpshion.devops.node.support.NodeContext;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.File;
import java.util.Map;

@Slf4j
@Component
public class OSSNode extends Node<OSSData> {

    @Resource
    private FileStorageService fileStorageService;

    @Override
    public NodeType nodeType() {
        return NodeType.OSS;
    }

    @Override
    public void handle(NodeContext nodeContext) throws Exception {
        log.info("OSSNode nodeContext:{}", nodeContext);
        sseHandle.sendMessage(nodeContext, new MsgData(MsgType.INFO, "开始执行oss节点"));

        Map<String, Object> contextData = nodeContext.getData();
        String workspace = contextData.get(NodeConstant.WORKSPACE).toString();

        OSSData data = getData(nodeContext);
        String path = data.getPath();
        if(path.contains("#workspace#")){
            path = path.replaceAll("#workspace#", workspace);
        }

        File file = new File(path);
        sseHandle.sendMessage(nodeContext, new MsgData(MsgType.INFO, "上传文件：" + file.getName() + " 文件地址：" + path));
        FileInfo upload = fileStorageService.of(file).setSaveFilename(file.getName()).upload();
        sseHandle.sendMessage(nodeContext, new MsgData(MsgType.INFO, "上传完成 result: " + upload.getUrl()));
        log.info("OSSNode upload:{}", upload);
    }

    @Override
    protected OSSData getData(NodeContext nodeContext) {
        NodeData nodeData = nodeContext.getNodeData();
        OSSData ossData = JSON.parseObject(JSON.toJSONString(nodeData.getData()), OSSData.class);
        return ossData;
    }
}
